import React, { useEffect, useState } from 'react';
import {  Form, Input, Modal, Select, message } from 'antd';
import { ADDCorridor, getBuildingsList } from '../request';
import { useIntl } from '@umijs/max';
const { Option } = Select;
interface Props {
    isModalOpen: boolean;
    handleOk: () => void;
    handleCancel: () => void;
}

const App: React.FC<Props> = ({ isModalOpen, handleCancel }) => {
    const intl = useIntl()
    const [form] = Form.useForm();
    const [selectedOptions, setSelectedOptions] = useState([]);
    function padSingleDigit(str: string | any[]) {
        if (str.length === 1) {
            return '0' + str;
        } else {
            return str;
        }
    }
    const handleOk = () => {
        form.validateFields().then(async (values): Promise<any> => {
            console.log(values)

            // if(!values.bname) return message.error("请选择楼栋")
            if (values.bname == undefined && values.floor == undefined) {
          
                let data = await ADDCorridor({
                    roomId: "00000000",
                    bname: "",
                    roomName: intl.formatMessage({ id: "FixLock.Main entrance door" }),
                    floor: "",
                })
                if (data.code == 0) {
                    message.success(intl.formatMessage({id:"RoomSettings.Added successfully!"}))
                    handleCancel()
                } else {
                    message.error(data.msg)
                }
            } else if (values.floor == undefined) {
                console.log(values.bname)

                if (values.bname == intl.formatMessage({ id: "FixLock.Main entrance door" })) {
                    let data = await ADDCorridor({
                        roomId: "FFFFFFFF",
                        bname: "",
                        roomName: intl.formatMessage({ id: "FixLock.Main entrance door" }),

                        floor: "",
                    })
                    if (data.code == 0) {
                        message.success(intl.formatMessage({id:"RoomSettings.Added successfully!"}))
                        handleCancel()
                    } else {
                        message.error(data.msg)
                    }
                } else {
                    let res2 = padSingleDigit(parseInt(values.bname).toString(16).toUpperCase().padStart(2, '0'))
                    console.log(res2)
                    let str = res2 + "000000"
                    let data = await ADDCorridor({
                        roomId: str,
                        bname: values.bname,
                        roomName: values.roomName,
                        floor: ""
                    })
                    if (data.code == 0) {
                        message.success(intl.formatMessage({id:"RoomSettings.Added successfully!"}))
                        handleCancel()
                    } else {
                        message.error(data.msg)
                        console.log(data.msg)
                    }
                }

            } else {

   
                if (values.bname == undefined) return message.error(intl.formatMessage({id:"RoomSettings.Please select a building"}))
                if (values.bname == intl.formatMessage({id:"RoomSettings.All"})) return message.error(intl.formatMessage({id:"RoomSettings.Please do not select all"}))
                
                let str = "" // roomid
                let res2 = padSingleDigit(parseInt(values.bname).toString(16).toUpperCase())
                let res = padSingleDigit(parseInt(values.floor).toString())
                str += res2 + parseInt(res).toString(16).toUpperCase().padStart(2, '0') + "0000"
                let data = await ADDCorridor({
                    roomId: str,
                    bname: values.bname,
                    roomName: values.roomName,
                    floor: values.floor
                })

                if (data.code == 0) {
                    message.success(intl.formatMessage({id:"RoomSettings.Added successfully!"}))
                    handleCancel()
                } else {
                    message.error(data.msg)
                }
            }



        }).catch((errorInfo) => {
            console.log('Failed:', errorInfo);
        });
    };
    const [Bon, setBon] = useState<any>([])
    const getlist = async () => {
        const buildlist = await getBuildingsList()

        if (buildlist.data.list) {
            const newBon = buildlist.data.list.map((item: { bno: React.SetStateAction<undefined> }) => item.bno);
            newBon.unshift(intl.formatMessage({id:"RoomSettings.All"}));

            setBon(newBon);
        }

    }
    useEffect(() => {
        getlist()
        getOption()
    }, [])
    const [optionArr, setoptionArr] = useState([])
    const getOption = () => {
        let arr = []
        for (let i = 1; i <= 100; i++) {
            if (i != 0) {

                arr.push(`${i}${intl.formatMessage({id:"RoomSettings.Layer"})}`)
            }
        }
        setoptionArr(arr)
    }
    const qishichen = (values: any) => {
        setSelectedOptions(values);

    };
    return (
        <>
            <Modal title={intl.formatMessage({ id: "RoomSettings.Add channel door" })}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                width={450}
            >

                <br />
                <Form
                    form={form}
                    name="basic"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    autoComplete="off"
                >
                    <Form.Item name="bname" label={intl.formatMessage({id:"FixLock.Building No"})}>
                        <Select
                            placeholder={intl.formatMessage({id:"RoomSettings.Please select a building"})}
                            allowClear
                        >
                            {
                                Bon.map((item: string, index: number) => {
                                    return (
                                        <Option key={index} value={item}>{item}{item == intl.formatMessage({id:"RoomSettings.All"}) ? "" : intl.formatMessage({id:"FixLock.building"})}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item<any>
                        label={intl.formatMessage({ id: "FixLock.Floor" })}
                        name="floor"

                    >
                        <Select
                            allowClear
                            style={{ width: '100%' }}
                            placeholder={intl.formatMessage({ id: "RoomSettings.Select Floor" })}
                            // disabled={qishichenFlag}
                            onChange={qishichen}
                            value={selectedOptions}
                        >
                            {
                                optionArr.map((item, index) => {
                                    return (
                                        <Option key={index} value={item}>{item}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item<any>
                        label={intl.formatMessage({ id: "FixLock.Channel name" })}
                        name="roomName"

                    >
                        <Input placeholder={intl.formatMessage({ id: "RoomSettings.Please enter channel" })} />
                    </Form.Item>

                </Form>

            </Modal>
        </>
    );
};

export default App; 